<template>
  <view class="login-container">
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <button type="primary" class="btn-login" @click="getUserProfile">一键登录</button>
    <text class="tips-text">登录后尽享更多权益</text>
  </view>
</template>

<script setup>
  import { ref } from 'vue';
import { useUser } from '../../store';
import {storeToRefs} from 'pinia'
  const userStore = useUser()
  const {redirectInfo} = storeToRefs(userStore)
  // 获取用户的基本信息
const getUserProfile = async()=>{
  const res = await uni.getUserProfile({desc:'用于完善会员资料或进行身份验证'}).catch(err => err)
  if(res.errMsg !== "getUserProfile:ok") return uni.$showMsg('您取消了授权')
  userStore.updateUserInfo(res.userInfo)
  getToken(res)
  
}
const getToken  = async (info)=>{
  // 获取code对应的值
  const res = await uni.login().catch(err=>err)
  if(res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
  const query = {
    code:res.code,
    encryptedData:info.encryptedData,
    iv:info.iv,
    rawData:info.rawData,
    signature:info.signature
    
  }
  const loginResult = await uni.$http.post('api/public/v1/users/wxlogin',query)
  if(loginResult.data.meta.status !==400) return uni.$showMsg('登录失败！')
  
  // 直接把token保存到仓库
  const token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
  // userStore.updateToken(loginResult.data.message.token)
  uni.$showMsg('登录成功！')
  userStore.updateToken(token)
  navigateBack()
}
// 登录之后回退一页
const navigateBack = ()=>{
  if(redirectInfo.value && redirectInfo.value.openType === 'switchTap'){
    uni.$showMsg('登录成功！即将跳转到购物车页')
    setTimeout(()=>{
      uni.switchTab({
        url:redirectInfo.value.from,
        complete: () => {
          userStore.updateRedirectInfo({})
        }
      })
    },1500)
  
  }
}
</script>

<style lang="scss">
.login-container{
  display: flex;
  height: 750rpx;
  background-color: #f8f8f8;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  &::after{
    content: ' ';
    display: block;
    width: 100%;
    background-color: white;
    position: absolute;
    bottom: 0;
    left: 0;
    border-radius: 100%;
    transform: translateY(50%);
    
  }
  .btn-login{
    width: 90%;
    border-radius: 100px;
    margin: 15px 0;
    background-color: #c00000;
  }
  .tips-text{
    font-size: 12px;
    color: gray;
  }
}
</style>